import { _decorator, Component, find, Label, Node, Sprite, SpriteFrame, tween, Tween, Vec3 } from 'cc';
import { ItemData } from '../Data';
import { NodeUtil } from '../AshFramework/Utils/NodeUtil';
import { ResourceUtil } from '../AshFramework/Utils/ResourceUtil';

const { ccclass, property } = _decorator;

@ccclass('PieceItem')
export class PieceItem extends Component {
    Icon: Sprite = null;
    BG: Node;
    ItemCountQuality: Node = null;
    ItemCountLabel: Label = null;

    protected onLoad(): void {
        this.Icon = find("Icon", this.node).getComponent(Sprite);
        this.BG = NodeUtil.GetNode("BG", this.node);
        this.ItemCountQuality = NodeUtil.GetNode("ItemCountQuality", this.node);
        this.ItemCountLabel = NodeUtil.GetComponent("ItemCountLabel", this.node, Label);
    }

    Init(data: ItemData, count: number, delay: number) {
        Tween.stopAllByTarget(this.node);
        this.node.setScale(Vec3.ZERO);
        this.BG.children.forEach(e => {
            if (e.name == `${data.Quality}`) e.getComponent(Sprite).grayscale = !data.IsUnlock;
        })

        this.ItemCountLabel.string = `×${count}`;

        this.BG.children.forEach(e => {
            e.active = e.name == `${data.Quality}`;
            if (e.name == `${data.Quality}`) e.getComponent(Sprite).grayscale = !data.IsUnlock;
        });

        this.ItemCountQuality.children.forEach(e => e.active = e.name == `${data.Quality}`);

        ResourceUtil.LoadSpriteFrame(`Items/${data.Index}`).then((sp: SpriteFrame) => this.Icon.spriteFrame = sp);

        tween(this.node).delay(delay).to(0.5, { scale: Vec3.ONE }, { easing: `backOut` }).call(() => { }).start();
    }

}